package com.nxk.modules.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nxk.modules.core.dao.SysUserDao;
import com.nxk.modules.core.entity.BaseEntity;
import com.nxk.modules.core.entity.SysParam;
import com.nxk.modules.core.entity.SysUser;
import com.nxk.modules.core.service.SysParamService;
import com.nxk.modules.core.service.SysUserService;
import com.nxk.modules.utils.Md5utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {


    @Autowired
    private SysParamService sysParamService;


    @Transactional(readOnly = false)
    public boolean save(SysUser sysUser) {
        if (StringUtils.isNotBlank(sysUser.getId())) {
            return super.updateById(sysUser);
        } else {
            SysParam sysParam = sysParamService.queryByKey("userInitPassword");
            String salt = Md5utils.randomSalt();
            sysUser.setUserCode(sysUser.getLoginCode());
            sysUser.setSalt(salt);
            //新增时,密码使用管理员设置的初始密码,加上随机盐值加密
            sysUser.setPassword(Md5utils.encryptPassword(sysUser.getLoginCode(), sysParam.getParamValue(), salt));
            return super.save(sysUser);
        }
    }


    /**
     * 用户重置密码
     */
    @Transactional(readOnly = false)
    public boolean initPwd(String userId){
        SysUser sysUser = new SysUser();
        SysUser byId = super.getById(userId);
        SysParam sysParam = sysParamService.queryByKey("userInitPassword");
        String salt =Md5utils.randomSalt();
        sysUser.setId(userId);
        sysUser.setSalt(salt);
        sysUser.setPassword(Md5utils.encryptPassword(byId.getLoginCode(), sysParam.getParamValue(), salt));
        return super.updateById(sysUser);
    }

    /**
     * 登陆时,根据loginCode查询用户,仅仅登陆
     * @param loginCode
     * @return
     */
    @Override
    public SysUser getUserByLoginCode(String loginCode) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>();
        queryWrapper.eq(SysUser::getLoginCode,loginCode);
        queryWrapper.select(
                SysUser::getId,
                SysUser::getUserCode,
                SysUser::getLoginCode,
                SysUser::getPassword,
                SysUser::getSalt,
                SysUser::getUserNick,
                SysUser::getUserImage,
                SysUser::getUserSex,
                SysUser::getUserPhone,
                SysUser::getUserEmail,
                SysUser::getUserRole,
                SysUser::getIsSystem,
                SysUser::getUserGrade,
                BaseEntity::getStatus
        );
        return super.getOne(queryWrapper);
    }



    /**
     * 仅用于个人中心修改密码时,查询用户原西悉尼
     * @param userId
     * @return
     */
    @Override
    public SysUser getUserPassWord(String userId) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>();
        queryWrapper.eq(SysUser::getId,userId);
        queryWrapper.select(
                SysUser::getId,
                SysUser::getLoginCode,
                SysUser::getPassword,
                SysUser::getSalt
        );
        return super.getOne(queryWrapper);
    }

    /**
     * 不分页查询所有用+户
     *
     * @param sysUser
     * @return
     */
    @Override
    public List<SysUser> listAll(SysUser sysUser) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("status", BaseEntity.STATUS_NORMAL, BaseEntity.STATUS_STOP);
        return super.list(queryWrapper);
    }

    /**
     * 批量分配用户角色
     *
     * @param userIds
     * @param roleCode
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public boolean roleUser(List<String> userIds, String roleCode) {
        List<SysUser> list = new ArrayList<>();
        userIds.stream().forEach(id -> {
            SysUser sysUser = new SysUser();
            sysUser.setId(id);
            sysUser.setUserRole(roleCode);
            list.add(sysUser);
        });
        return super.updateBatchById(list);
    }


    public IPage<SysUser> page(SysUser sysUser) {
        IPage<SysUser> page = new Page<SysUser>(sysUser.getPageNo(), sysUser.getPageSize());
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
        if (StringUtils.isNotBlank(sysUser.getUserNick())) {
            queryWrapper.lambda().like(SysUser::getUserNick, sysUser.getUserNick());
        }
        if (StringUtils.isNotBlank(sysUser.getLoginCode())) {
            queryWrapper.lambda().like(SysUser::getLoginCode, sysUser.getLoginCode());
        }
        if (StringUtils.isNotBlank(sysUser.getUserPhone())) {
            queryWrapper.lambda().like(SysUser::getUserPhone, sysUser.getUserPhone());
        }
        if (StringUtils.isNotBlank(sysUser.getUserEmail())) {
            queryWrapper.lambda().like(SysUser::getUserEmail, sysUser.getUserEmail());
        }
        if (StringUtils.isNotBlank(sysUser.getIsSystem())) {
            queryWrapper.lambda().eq(SysUser::getIsSystem, sysUser.getIsSystem());
        }
        if (StringUtils.isNotBlank(sysUser.getUserGrade())) {
            queryWrapper.lambda().eq(SysUser::getUserGrade, sysUser.getUserGrade());
        }
        //queryWrapper.setEntity(sysUser);
        queryWrapper.orderByDesc("create_date").in("status", 1, 2);
        IPage<SysUser> result = super.page(page, queryWrapper);
        return result;
    }

    @Transactional(readOnly = false)
    public boolean deleteById(String id) {
        return super.removeById(id);
    }


}
